package com.tang.websocket.j2ee;

import com.tang.websocket.ConfigTest;
import com.tang.websocket.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author Tang
 * @classname SimpleWebSocket
 * @description [ 多例的 ]
 * @date 2021/9/26 15:02
 */
@Component
@ServerEndpoint(value = "/simple/{id}")
public class SimpleWebSocket {

    private User user;

//    @OnOpen
//    public void open(@NotNull @PathParam("id") String id, Session session) {
//        user = new User(Integer.parseInt(id));
//        System.out.println("user id:" + id);
//        System.out.println("user id:" + id);
//    }

    private static ConfigTest configTest;

    @Autowired
    public void setConfigTest(ConfigTest configTest) {
        SimpleWebSocket.configTest = configTest;
    }

    @OnOpen
    public void open(@NotNull Session session) {
        String id = session.getPathParameters().get("id");
        System.out.println("user id:" + id);
        this.user = new User(Integer.valueOf(id));
        System.out.println(configTest);
    }

    @OnMessage
    public void message(String message, Session session) {
        System.out.println("current:[" + this.user + "]--->" + message);
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("websocket 睡眠结束！");
    }

    @OnClose
    public void close(Session session) {
        try {
            System.out.println("current:[" + this.user + "]--->close...");
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void error(Session session, Throwable e) {
        System.out.println("current:[" + this.user + "]");
        System.out.println(e.getMessage());
    }

}